package com.ishopping.web.manage.controller;

import com.github.pagehelper.PageInfo;
import com.ishopping.common.core.base.constant.CommonConstants;
import com.ishopping.common.core.base.controller.BaseController;
import com.ishopping.api.manage.entity.Role;
import com.ishopping.api.manage.entity.RolePermission;
import com.ishopping.api.manage.service.IRolePermissionService;
import com.ishopping.api.manage.service.IRoleService;
import com.ishopping.common.core.base.enums.ReturnEnum;
import com.ishopping.common.core.vo.DataGridResult;
import com.ishopping.common.core.vo.JsonResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 角色controller
 */
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    /**
     * 默认页面
     */
    @RequiresPermissions("system:role:manage")
    @RequestMapping(value = "/manage", method = RequestMethod.GET)
    public String roleManager() {
        return "system/roleMgt";
    }

    /**
     * 获取角色列表
     */
    @RequiresPermissions("system:role:manage")
    @RequestMapping(value="/list",method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<DataGridResult> roleList(HttpServletRequest request, Role role) {
        try {
            int currentPage = Integer.valueOf(request.getParameter("page"));
            int pageSize = Integer.valueOf(request.getParameter("rows"));
            PageInfo page = roleService.queryPageListByWhere(role, currentPage, pageSize);
            DataGridResult dataGrid = new DataGridResult(page.getTotal(), page.getList());
            return ResponseEntity.ok(dataGrid);
        } catch (Exception e) {
            LOGGER.error("查询角色列表出错!" , e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * 添加角色跳转
     * @param model
     */
    @RequiresPermissions("system:role:add")
    @RequestMapping(value = "/addForm", method = RequestMethod.GET)
    public String addRoleForm(Model model) {
        model.addAttribute("role", new Role());
        model.addAttribute("action", CommonConstants.ADD);
        return "system/roleForm";
    }

    /**
     * 添加角色
     * @param role
     */
    @RequiresPermissions("system:role:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object addRole(Role role) {
        //int result = roleService.create(role);
        int result = roleService.save(role);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 修改角色跳转
     * @param id
     * @param model
     * @return String
     */
    @RequiresPermissions("system:role:update")
    @RequestMapping(value = "/updateForm/{id}", method = RequestMethod.GET)
    public String updateRoleForm(@PathVariable("id") Long id, Model model) {
        //model.addAttribute("role", roleService.findById(id));
        model.addAttribute("role", roleService.queryById(id));
        model.addAttribute("action", CommonConstants.UPDATE);
        return "system/roleForm";
    }

    /**
     * 修改角色
     * @param role
     * @return Object
     */
    @RequiresPermissions("system:role:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateRole(Role role) {
        int result = roleService.updateSelective(role);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 删除角色
     * @param id
     * @return Object
     */
    @RequiresPermissions("system:role:delete")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object deleteRole(@PathVariable("id") Long id) {
        //int result = roleService.deleteById(id);
        int result = roleService.deleteById(id);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 角色添加权限跳转
     * @param model
     * @param roleId
     * @return String
     */
    @RequiresPermissions("system:role:assignPermission")
    @RequestMapping(value = "/{roleId}/assignPermissionForm")
    public String getRolePermission(Model model, @PathVariable("roleId") Long roleId) {
        model.addAttribute("roleId", roleId);
        return "system/assignPermission";
    }

    /**
     * 修改角色拥有的权限
     * @param roleId
     * @param newPermList
     * @return Object
     */
    @RequiresPermissions("system:role:assignPermission")
    @RequestMapping(value = "/{roleId}/assignPermission")
    @ResponseBody
    public Object updateRolePermission(@PathVariable("roleId") Long roleId, @RequestBody List<Long> newPermList) {
        int result = rolePermissionService.save(roleId, newPermList);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 获取角色拥有的权限
     * @param roleId
     * @return String
     */
    @RequiresPermissions("system:role:assignPermission")
    @RequestMapping(value = "/{roleId}/permission")
    @ResponseBody
    public List<RolePermission> getRolePermissionList(@PathVariable("roleId") Long roleId) {
        return rolePermissionService.findRolePermissionsByRoleId(roleId);
    }
}
